<?php
class PhotoUploadControl extends FileUploadControl
{
    protected $id;
    protected $model;
    protected $field;
    protected $size;

    public function PhotoUploadControl($id, $modelName, $field, $size = null)
    {
        $this->id = $id;
        $this->model = ModelBase::GetInstanceByName($modelName);
        $this->field = $field;
        $this->size = $size ? $size : Photo::GetInstance()->SIZE_SMALL;
        $this->name = $modelName.'_'.$field;
        parent::__construct("?__cr=PhotoUploadControl/$id/$modelName/$field&action=SavePhoto");
    }

    public function Render()
    {
        if (RequestHandler::IsExisted($this->name))
            $this->SavePhoto();

        $photo = $this->model->FindScalarById($this->id, $this->field);
        $url = $photo ? Photo::GetInstance()->GetUrl($photo, $this->size) : null;
        $this->Replace('url_photo', $url);
        return parent::Render();
    }

    public function SavePhoto()
    {
        try
        {
            $old = $this->model->FindScalarById($this->id, $this->field);
            $photo = Photo::GetInstance()->SaveUploadedPhoto();
            $item['id'] = $this->id;
            $item[$this->field] = $photo;
            $this->model->Update($item);
            Photo::GetInstance()->Delete($old);
            MessageBase::Confirm('Photo has been saved');
            RequestHandler::Back();
        }
        catch (Exception $ex)
        {
            MessageBase::Warning($ex->getMessage());
        }
    }
}
?>